<?php
/**
 * Created by PhpStorm.
 * User: Steven
 * Date: 2017/7/10
 */

namespace app\common\behavior;


use app\classes\model\ClassModel;
use app\financial\model\OrderModel;
use think\Db;
use think\Log;

class CronRunBehavior
{
    //行为扩展的执行入口必须是run
    public function run(&$params) {
        if (config('cron_config_on')) {
            $this -> checkTime();
        }
    }

    private function checkTime()
    {
        $is_exec = false;
        $timestamp = 0;
        //间隔秒（0为一直运行）
        $cron_expire = config('cron_config_expire');

        $init_time = session('CRON_TIME');
        if(isset($init_time) && is_numeric($init_time)){
            if(time() > $init_time){
                $timestamp = intval($init_time) + intval($cron_expire);
                if($timestamp < time()){
                    //销毁原有session
                    session('CRON_TIME',null);
                    //重新设置任务执行时间间隔
                    $timestamp = time() + intval($cron_expire);
                }
                session('CRON_TIME',$timestamp);

                //执行任务标记
                $is_exec = true;
            }
        }else{
            //设置任务执行时间间隔
            $timestamp = time() + intval($cron_expire);
            session('CRON_TIME',$timestamp);
            //执行任务标记
            $is_exec = true;
        }

        //执行任务
        if($is_exec) {
            //取消过期订单
            $this->cancelOrder();
            //指定开始时间
            $log = 'Cron['.date('Y-m-d H:i:s').']: cron_expire=' .date('Y-m-d H:i:s', $timestamp). "\r\n";
            cmf_log($log,"cron_log.txt");

        }
    }

    /**
     * 取消过期订单
     * @param int $shop_id
     */
    public function cancelOrder($shop_id=1)
    {
        $order_mdl = new OrderModel();
        $where = [
            'shop_id' => ['=', $shop_id],
//            'delete_time' => ['=', 0],
            'order_status' => ['=', 0],//待支付
            'cancel_time' => ['<=', time()],//订单过期
        ];

        $orders = $order_mdl->where($where)->select();
        if(count($orders) > 0){
            $orders = $orders->toArray();
            foreach ($orders as $order) {
                //订单已过期，修改订单状态,同时释放座位，优惠返回等相关操作
                $update_data = [
                    'order_status' => 3,//已取消
                    'update_time' => time(),
                ];
                //修改订单
                Db::name('order')->where('id',$order['id'])->update($update_data);

                //释放座位
                $class_mdl = new ClassModel();
                $class_mdl->releaseSeat($order['class_id'], $order['student_id'], $shop_id);

                //释放优惠
                $award_where = [
                    'student_id' => $order['student_id'],
                    'order_id' => $order['id'],
                ];
                $seat = Db::name('award_order')->where($award_where)->find();
                if(count($seat) > 0) {
                    Db::name('award_order')->where($award_where)->delete();
                }
            }
        }

//        $order_mdl->where($where)->chunk(100, function($orders) use($order_mdl,$shop_id) {});
    }

}